
package org.movee.spring.data.hugegraph.gremlin;

import org.movee.spring.data.hugegraph.exception.HugeInvalidEntityIdFieldException;
import org.movee.spring.data.hugegraph.exception.HugeUnSupportedDataTypeException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

import java.io.PrintWriter;
import java.io.StringWriter;


@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public class GremlinUtils {

    public static String quoteIfNeeded(final Object o) {

        if (o == null) {
            return "null";
        }

        if (String.class.isInstance(o)) {
            return String.format("'%s'", o);
        } else if (o.getClass().isPrimitive()) {
            return String.format("%s", o);
        } else if (Number.class.isAssignableFrom(o.getClass())) {
            return String.format("%s", o);
        } else if (Boolean.class.isInstance(o)) {
            return String.format("%s", o);
        } else if (o.getClass().isEnum()) {
            return String.format("'%s'", o);
        }

        // 只支持上面的几种数据类型，List、array等暂不支持
        String s = String.format("unsupported data type, class: %s", o.getClass().toString());
        throw new HugeUnSupportedDataTypeException(s);
    }

    public static String idAsString(final Object id) {
        if (id instanceof String) {
            return String.format("'%s'", (String) id);
        } else if (id instanceof Integer) {
            return String.format("%d", (Integer) id);
        } else if (id instanceof Long) {
            return String.format("%d", (Long) id);
        }

        throw new HugeInvalidEntityIdFieldException("Only String/Integer/Long of id is supported");

    }

    public static String strExceptionStack(@NonNull final Throwable t) {
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        return sw.toString();
    }

}
